package com.wanxi.util;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 步骤
 * 1.加载驱动
 * 2.取得连接
 * 3.编译sql
 * 4.执行sql
 * 5.返回结果
 * 6.关闭连接
 */
public class JDBC {
    private JDBC() {
    }

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static Connection connection = null;
    private static final String URL = "jdbc:mysql://121.199.55.96:3306/canyin04?serverTimezone=UTC&characterEncoding=UTF-8";
    private static final String USER = "canyin04";
    private static final String PASS = "123456";
    private static PreparedStatement preparedStatement = null;
//    private static Statement statement=null;

    /**
     * 取得连接
     *
     * @return
     */
    private static Connection getConn() {
        if (connection == null) {
            try {
                connection = DriverManager.getConnection(URL, USER, PASS);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

    public static void main(String[] args) {
        System.out.println(getConn());
    }

    public static int update(String sql,List<Object> list) {
        try {
            preparedStatement = getConn().prepareStatement(sql);
//            List<Object> list = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                preparedStatement.setObject(i + 1, list.get(i));
            }
//            preparedStatement.setObject(1, "");
//            preparedStatement.setObject(2, "");
//            preparedStatement.setObject(3, "");
//            preparedStatement.setObject(4, "");
//            preparedStatement.setObject(5, "");
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public static ResultSet query(String sql) {
        try {
            preparedStatement = getConn().prepareStatement(sql);
            return preparedStatement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void close() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
